import { debug } from './config'
import { loginByTicket } from '../api/common' 
import { Message, } from '@arco-design/web-react';

// 将url在？后面的参数分割以key : value的形式存到obj返回
export function parseQueryString(url) {
    const obj = {}
    if (url.indexOf('?') !== -1) {
      const str = url.split('?')[1]
      const strs = str.split('&')
      strs.map((item, i) => {
        const arr = strs[i].split('=')
        obj[arr[0]] = arr[1]
      })
    }
    return obj
}

export const creatAjaxAction = (createApi , startAction, endAction, rejectAction) => (reqset = {}, resolve, reject, config) => (dispatch) => {
    if (startAction) dispatch(startAction({ req: reqset, res: {} }))
    const _resolve = (res) => { 
        if (endAction) dispatch(endAction({req: reqset, res: res}))
        if (resolve) resolve(res) 
    }
    const _reject = (res) => { 
        if (rejectAction) dispatch(rejectAction({loading: false}))
        if (reject) reject() 
    }
    return createApi(reqset, _resolve, _reject, config)
}

// 打印
export function log(...obj){
    if (debug){
        console.log(...obj)
    }
}

export const validateTickit = async function validateTickit({ state, pathname }, callback) {
    const { ticket } = state
    // 如果存在ticket
    if (ticket) {
      const loginInfo = await _fetchLoginByTicket(ticket)
      sessionStorage.setItem('token', loginInfo.token)
      // sessionStorage.setItem('isLeftNavMini', false)
    } else {
      /**
       * 仅存在于以下两种情况：
       * 1. 未登录，退出到登录页面进行登录操作，在登录时获取菜单并存到sessionStorage中，再进行页面跳转，执行此代码时只需要请求staff信息
       * 2. 登录过，刷新页面后执行此代码，认为上次登录时已经获取过菜单并已存到sessionStorage中，所以只需要请求staff信息
       *    (FIXME:网速缓慢的情况下，可能存在登录token拿到后，菜单数据返回前，直接输入url访问页面的情况，所以会导致获取不到菜单)
       */
      // await _fetchStaff()
      // if (typeof callback === 'function')callback()
      /*
      _fetchStaff()
      _fetchNav(callback)
      */
    }
  
    // 我取消了******
    // const _a = _fetchStaff()
    // const _b = _fetchNav(pathname)
    // await _a
    // await _b
    // if (typeof callback === 'function') callback()
}

/* --------------验证ticket并获取用户信息和菜单信息 --------------*/
const _fetchLoginByTicket = async ticket => new Promise((resolve) => {
    loginByTicket({ ticket }, (response) => {
        resolve(response.data)
    }, (response) => {
        const obj = parseQueryString(window.location.href)
        console.log(obj)
        if (obj.ticket || obj.mode) {
        Message.info('登录过期或服务不可用')
        } else {
        // hashHistory.replace('/login')
        }
    })
})
